<template>
  <div class="dict">
    <div class="search-term">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item>
          <el-input
            placeholder="请输入字典名称"
            v-model="searchInfo.keyName"
            clearable
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="请输入字典值"
            v-model="searchInfo.dictKey"
            clearable
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item prop="status">
          <el-select
            v-model="searchInfo.status"
            placeholder="请选择"
            clearable
            size="small"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="onSubmit" type="primary" size="small"
            >搜 索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button @click="openDialog('add')" size="small">新 增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" style="width: 100%;margin-bottom: 10px;" border>
      <el-table-column prop="keyName" label="字典名称" align="center">
      </el-table-column>
      <el-table-column prop="dictKey" label="字典值" align="center">
      </el-table-column>
      <el-table-column prop="status" label="启用状态" align="center">
        <!-- <template slot-scope="scope">
          <span :class=" scope.row.status == 1 ? 'green' : 'red' ">{{scope.row.status == 1? '开启':'禁用'}}</span>
        </template> -->
        <template slot-scope="scope">
          <span v-if="scope.row.status === '2'" class="defaults"
            >暂未配置值</span
          >
          <span v-else :class="[scope.row.status === '1' ? 'green' : 'red']">
            <i
              :class="[
                scope.row.status === '1'
                  ? 'el-icon-video-pause '
                  : 'el-icon-video-play',
              ]"
              style="padding: 0 5px;cursor:pointer;"
              @click="iconClick(scope.row)"
            ></i
            >{{ scope.row.status === "1" ? "开启" : "禁用" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" width="200px">
        <template slot-scope="scope">
          <!-- <el-button
            @click="handleEdit(scope.row)"
            size="small"
            type="primary"
            icon="el-icon-plus"
            >新增子节点</el-button
          > -->
          <el-button @click="handleEdit(scope.row)" size="small" type="text"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.status === '2'"
            @click="handleConfig(scope.row)"
            size="small"
            type="text"
            >字典配置</el-button
          >
          <el-button @click="deleteDicts(scope.row)" size="small" type="text"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currPage"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 50, 100]"
      :style="{ float: 'right', padding: '20px' }"
      :total="totalCount"
      @current-change="handlepageChange"
      @size-change="handleSizeChange"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 新增 -->
    <el-dialog
      :before-close="closeDialog"
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      class="dialogs"
      width="380px"
    >
      <el-form :model="form" :rules="rules" label-width="80px" ref="areaForm">
        <el-form-item label="字典名称" prop="keyName">
          <el-input
            autocomplete="off"
            v-model="form.keyName"
            size="small"
            placeholder="请输入字典名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典值" prop="dictKey">
          <el-input
            autocomplete="off"
            v-model="form.dictKey"
            size="small"
            placeholder="请输入代码"
            :disabled="type === 'edit'"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer" slot="footer">
        <el-button @click="closeDialog" size="small">取 消</el-button>
        <el-button @click="enterDialog" type="primary" size="small"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 字典配置 -->
    <el-drawer
      title=""
      :visible.sync="configDialog"
      direction="rtl"
      size="60%"
      id="drawer"
    >
    <h3 style="position:absolute;top:25px;left:20px;color:#72767b;font-weight:normal;">字典配置</h3>
     <el-form :model="{ gridData }" ref="ruleForm"> 
        <el-table :data="gridData" style="width: 100%" border>
          <el-table-column
            prop="dictName"
            label="名称"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="`gridData.${scope.$index}.dictName`"
                required
              >
                <el-input v-model="scope.row.dictName" size="small"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            prop="dictValue"
            label="数值"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="`gridData.${scope.$index}.dictValue`"
                required
              >
                <el-input v-model="scope.row.dictValue" size="small"></el-input>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column
            prop="sortBy"
            label="排序"
            align="center"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="`gridData.${scope.$index}.sortBy`"
                required
              >
                <el-input-number
                v-model="scope.row.sortBy"
                :min="1"
                controls-position="right"
                :max="100"
                size="small"
              ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="70" align="center">
            <template slot="header">
              <el-button type="text" @click="doAdd">增加</el-button>
            </template>

            <template slot-scope="scope">
              <el-button type="text" size="small" @click="doDel(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div style="text-align:center;margin-top:15px;" v-if="gridData.length>0">
        <el-button @click="closeDict" size="small">取消</el-button>
        <el-button type="primary" @click="submitData" size="small">确定</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
// 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索
import { cloneDeep } from 'lodash'
import { DictList, addDict,editDict,configDict,getConfigDict,deleteDict } from "@/api/sysDictionary";
import infoList from "@/components/mixins/infoList";
export default {
  name: "Area",
  mixins: [infoList],
  data() {
    return {
      gridData: [],
      configDialog: false,
      statusOptions: [
        {
          value: 0,
          label: "禁用",
        },
        {
          value: 1,
          label: "开启",
        },
      ],
      listApi: DictList,
      dialogFormVisible: false,
      dialogTitle: "新增地区",
      form: {
        // path: '',
        // apiGroup: '',
        // method: '',
        // description: ''
        name: "",
        parentId: "",
        areaId: "",
        sortBy: 1,
        status: 1,
      },
      dictKeyId:'',
      type: "",
      rules: {
        keyName: [
          { required: true, message: "请输入字典名称", trigger: "blur" },
        ],
        dictKey: [{ required: true, message: "请输入代码", trigger: "blur" }],
      },
    };
  },
  methods: {
    /**
     * 新增
     */
    doAdd() {
      this.gridData.push({
        dictName: '',
        dictValue: '',
        sortBy: this.getMaxDictSort() + 1
      })
    },
    /**
     * 获取当前最大的sort字段值
     */
    getMaxDictSort() {
      let maxDictSort = 0
      const { length } = this.gridData
      if (length) {
        const sortedTableData = cloneDeep(this.gridData).sort(
          (a, b) => a.sortBy - b.sortBy
        )
        maxDictSort = sortedTableData[length - 1].sortBy
      }
      return maxDictSort
    },
    /**
     * 删除
     */
     doDel(index) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
         this.gridData.splice(index, 1)
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      
    },
    /**
     * 提交
     */
    async submitData() {
      this.btnLoading = true
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
        const res = await configDict(this.dictKeyId,this.gridData);
        if (res.statusCode === 0) {
            this.$message({
              type: "success",
              message: "提交成功",
            });
            this.configDialog = false 
            this.getTableData();
          } 
        } else {
          this.$message.error('有字段没有填写完整，请检查')
          return false
        }
      })
    },
    closeDict(){
      this.configDialog = false
    },
    //字典配置
    async handleConfig(row) {
      // console.log(row)
      this.dictKeyId = row.dictKeyId
      const res = await getConfigDict(row.dictKeyId)
      console.log(res)
      this.configDialog = true;
    },
    //条件搜索前端看此方法
    onSubmit() {
      this.page = 1;
      this.pageSize = 10;
      this.getTableData();
    },
    initForm() {
      this.$refs.areaForm.resetFields();
      this.form = {
        path: "",
        apiGroup: "",
        method: "",
        description: "",
      };
    },
    closeDialog() {
      this.initForm();
      this.dialogFormVisible = false;
    },
    openDialog(type) {
      switch (type) {
        case "add":
          this.dialogTitle = "新增数据字典";
          break;
        case "edit":
          this.dialogTitle = "编辑数据字典";
          break;
        default:
          break;
      }
      this.type = type;
      this.dialogFormVisible = true;
    },
    handleEdit(row) {
      // const res = await getApiById({ id: row.ID })
      this.form = row;
      // console.log(this.form)
      this.openDialog("edit");
    },
    async deleteDicts(row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteDict(row.dictKeyId);
          if (res.statusCode == 0) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getTableData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async enterDialog() {
      this.$refs.areaForm.validate(async (valid) => {
        if (valid) {
          switch (this.type) {
            case "add":
              {
                // console.log(this.form)
                const { keyName, dictKey } = this.form;
                const res = await addDict({ keyName, dictKey });
                if (res.statusCode == 0) {
                  this.$message({
                    type: "success",
                    message: "添加成功",
                    showClose: true,
                  });
                }
                this.getTableData();
                this.closeDialog();
              }

              break;
            case "edit":
              {
                const { keyName, dictKey,dictKeyId} = this.form;
                const res = await editDict({ keyName, dictKey,dictKeyId });
                if (res.statusCode == 0) {
                  this.$message({
                    type: "success",
                    message: "编辑成功",
                    showClose: true,
                  });
                }
                this.getTableData();
                this.closeDialog();
              }
              break;
            default:
              {
                this.$message({
                  type: "error",
                  message: "未知操作",
                  showClose: true,
                });
              }
              break;
          }
        }
      });
    },
  },
  filters: {
    methodFiletr(value) {
      const target = methodOptions.filter((item) => item.value === value)[0];
      // return target && `${target.label}(${target.value})`
      return target && `${target.label}`;
    },
    tagTypeFiletr(value) {
      const target = methodOptions.filter((item) => item.value === value)[0];
      return target && `${target.type}`;
    },
  },
  created() {
    this.getTableData();
  },
};
</script>
<style lang="scss">
.defaults {
  color: #909399;
}
.green {
  color: #67c23a;
}
.red {
  color: #f56c6c;
}
.button-box {
  // padding: 10px 20px;
  .el-button {
    float: right;
  }
}
.el-tag--mini {
  margin-left: 5px;
}

.dialogs {
  ::v-deep .el-dialog__body {
    padding: 15px 20px 10px 20px;
  }
  ::v-deep .el-input__inner {
    width: 225px;
  }
  ::v-deep .el-textarea__inner {
    width: 225px;
  }
  .dialog-footer {
    text-align: center;
  }
  ::v-deep .el-input-number .el-input__inner {
    width: 130px;
  }
}
.warning {
  color: #dc143c;
}
.dict-config-draw {
  .el-input-number {
    width: 180px;
  }
  .el-form-item {
    margin-bottom: 0 !important;
  }
}
#drawer {
  .el-table__row{
    .cell{
      height:36px !important;
    }
  }
}
</style>
